package top.linruchang.util.translate;

import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import top.linruchang.bean.YouDaoYunTranslateApiParam;
import top.linruchang.util.HttpUtil;

import java.io.InputStream;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * 作用：有道云翻译
 *
 * @author LinRuChang
 * @version 1.0
 * @date 2020/11/05
 * @since 1.8
 */
public class YouDaoYunTranslate implements TranslateInterface {

    private static final String TRANSLATE_URL = "https://openapi.youdao.com/api";

    /**
     * <p>
     * description: 将中文翻译成英文
     * </p>
     *
     * @param sourceTest 需要被翻译的中文
     * @return java.lang.String 翻译结果
     */
    @Override
    public  String translate(String sourceTest) {
        String result = null;
        YouDaoYunTranslateApiParam youDaoYunTranslateApiParam = new YouDaoYunTranslateApiParam().setQ(sourceTest);
        youDaoYunTranslateApiParam.signSetting();
        InputStream inputStream = null;
        try {
            //获取响应体
            inputStream = HttpUtil.sendRequest(TRANSLATE_URL, youDaoYunTranslateApiParam);
            String responseResult = new String(IoUtil.readBytes(inputStream));
            //解析响应体
            JSONObject parse = (JSONObject) JSON.parse(responseResult);
            result =  parse.getJSONArray("translation").getString(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * <p>
     * description: 将多个中文翻译成英文 - 并用Map进行存储 key原文 value翻译结果
     * </p>
     *
     * @param sourceTests 多个需要被翻译的文本
     * @return java.util.Map<java.lang.String,java.lang.String>
     */
    @Override
    public  Map<String, String> translate(Collection<String> sourceTests) {
        Map<String, CompletableFuture<String>> collect = sourceTests.stream()
                .distinct()
                .collect(Collectors.toMap(sourceTest -> sourceTest, sourceTest ->
                        CompletableFuture.supplyAsync(() -> translate(sourceTest.trim()))
                ));
        Map<String, String> result = collect.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().join()));
        return result;
    }


}
